import _ from "lodash";
import { DefineComponent, App } from "vue";

// 假设我们有一个自定义的类型来表示 Vue 组件
export type VueComponent = DefineComponent<{}, {}, any>;
// 定义一个接口来表示我们的组件库
export interface ComponentLibrary {
    [key: string]: VueComponent;
}
export interface ICompInst {
    cmpnts: ComponentLibrary;
    cmpntPrefix: string;
    addComponents(modules: Record<string, { default: VueComponent }>, prefix?: string): void;
    addComponent(name: string, component: VueComponent, prefix: string): void;
    install(app: App): void;
}

// CompInst 类
export class CompInst {
    public cmpnts: ComponentLibrary = {};
    public cmpntPrefix: string = "x-";

    constructor(modules: Record<string, { default: VueComponent }> | null, prefix: string = "x-") {
        this.cmpntPrefix = prefix;
        if (!modules || _.isEmpty(modules)) return;
        this.addComponents(modules, prefix);
    }
    public addComponents(modules: Record<string, { default: VueComponent }>, prefix: string = "x-") {
        // 遍历 modules 并构建组件库
        for (const fullPath in modules) {
            const lastName = _.last(fullPath.split("/"));
            if(lastName?.startsWith('_')){
                console.log('ignore', fullPath);
                continue;
            }
            const componentName = _.camelCase(lastName?.replace(/\.vue$/, ""));
            this.addComponent(componentName, modules[fullPath].default, prefix);
        }
    }
    public addComponent(name: string, component: VueComponent, prefix: string = "x-") {
        const fileName = (prefix ?? this.cmpntPrefix) + name;
        const componentName = _.camelCase(fileName.replace(/\.vue$/, ""));
        this.cmpnts[componentName] = component;
    }

    // 定义 install 方法，接收 Vue 应用实例作为参数
    public install(app: App) {
        // 遍历组件库并注册每个组件
        for (const name in this.cmpnts) {
            app.component(name, this.cmpnts[name]);
        }
    }
}

